package cn.tedu.charging.order.handler;

import cn.tedu.charging.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("捕获MethodArgumentNotValidException",e);
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuffer allMessage = new StringBuffer();
        for(FieldError fieldError : fieldErrors){
            String defaultMessage = fieldError.getDefaultMessage();
            allMessage.append(defaultMessage);
            allMessage.append(",");
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg(delLastChar(allMessage));
        jsonResult.setCode(4000);
        return jsonResult;
    }

    private String delLastChar(StringBuffer message){
        Integer start = message.length() - 1;
        Integer end = message.length();
        message.delete(start, end);
        return message.toString();
    }
}
